/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.uoc.tdp.pac4.cliente;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Locale;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import edu.uoc.tdp.pac4.i18n.TDSLanguageUtils;
import edu.uoc.tdp.pac4.beans.Preu_peca;
import edu.uoc.tdp.pac4.beans.Proveidor;
import edu.uoc.tdp.pac4.comun.GestorInterface;
import edu.uoc.tdp.pac4.comun.Utils;

/**
 *
 * @author pguerreroj
 */
public class ConsultaPreus extends JInternalFrame{
    
    private JPanel p;
    private JLabel jLabel;
    private JLabel jLabel1;
    private JLabel jLabel2;
    private JLabel jLabel3;
    private JLabel jLabel4;
    private JComboBox jComboBox;
    private JTable tabla;
    private DefaultTableModel model;
    private JButton jButton1;
    private GestorInterface gestorPreus;
    private final String URL = "localhost";
    private final String JNDI_NAME ="CATL";
    private final int PORT = 1099;
    String [] titulos ={"Marca","Tipus","Preu"};
    
    public ConsultaPreus(){
        initComponents();
        seleccionDeIdioma();
        initComboProveidors();
    }
    
    private void seleccionDeIdioma() {
        Locale localLocale = new Locale("es", "ES");
        TDSLanguageUtils.setDefaultLanguage("i18n/messages");
    }
    
    public void initComponents(){
        this.setTitle(TDSLanguageUtils.getMessage("Consulta.Titulo"));
        p= new JPanel();
        p.setLayout(null);
        //etiqueta 
        this.jLabel = new JLabel();
        this.jLabel.setBounds(new Rectangle(10, 10, 100, 30));
        this.jLabel.setText(TDSLanguageUtils.getMessage("Consulta.Proveedor"));
        p.add(jLabel);
        //combo proveidors
        this.jComboBox = new JComboBox();
        this.jComboBox.setBounds(new Rectangle(110, 10, 150, 30));
        this.add(jComboBox);
        this.jLabel1 = new JLabel();
        this.jLabel1.setBounds(new Rectangle(10, 40, 100, 30));
        this.jLabel1.setText(TDSLanguageUtils.getMessage("Consulta.Descuento"));
        p.add(jLabel1);
        //label descuento
        this.jLabel3 = new JLabel("0.0");
        this.jLabel3.setBounds(new Rectangle(90, 40, 100, 30));
        p.add(jLabel3);
        //etiqueta 2
        this.jLabel2 = new JLabel();
        this.jLabel2.setBounds(new Rectangle(110, 40, 180, 30));
        this.jLabel2.setText(TDSLanguageUtils.getMessage("Consulta.Pedidos"));
        p.add(jLabel2);
        //label quantitat
        this.jLabel4 = new JLabel("0");
        this.jLabel4.setBounds(new Rectangle(220, 40, 100, 30));
        p.add(jLabel4);
        
        model = new DefaultTableModel(null, titulos);
        final JTable table = new JTable();
        //boton ver
        this.jButton1=new JButton();
        this.jButton1.setBounds(new Rectangle(310, 10, 150, 30));
        this.jButton1.setText(TDSLanguageUtils.getMessage("Consulta.consultar"));
        this.jButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent paramAnonymousActionEvent) {
                        ArrayList<Preu_peca> lista = new ArrayList();
                        model = new DefaultTableModel(null, titulos){
                            @Override
                            public boolean isCellEditable(int row, int column) {
                                return false;
                            }
                        };
                        ConsultaPreus.this.conectarServerRMI();
                        try{
			    LocalProveidor lp = (LocalProveidor) jComboBox.getSelectedItem();
                            lista =ConsultaPreus.this.gestorPreus.getPreusByProveidor(lp.getId());
                            if(lista.isEmpty()){
                                Utils.shownError(TDSLanguageUtils.getMessage("Consulta.ErrorNoRecurso"));
                                //System.exit(0);
                            }else{
                                montarTabla(lista);
                                mostrarDescuentoCantidad(lista.get(0).getProveidor());
                                table.setModel(model); 

                            }
                         }catch (RemoteException localRemoteException) {
                             Utils.shownError(TDSLanguageUtils.getMessage("Aplication.ExcpGenRemota"));
                         }catch (SQLException e) {
                             Utils.shownError(TDSLanguageUtils.getMessage("Consulta.ConsultaBD"));
                         }
                    }
            
        });
        p.add(jButton1);
        table.setPreferredScrollableViewportSize(new Dimension(500, 200));
        table.setFillsViewportHeight(true);
        table.setBounds(10, 100, 500, 200);
        table.setModel(model);
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(10, 100, 500, 200);
        //Add the scroll pane to this panel.
        p.add(scrollPane);
        add(p);
        pack();       
        this.setResizable(true);
        this.setClosable(true);
        this.setIconifiable(true);
        this.setMaximizable(true);
        this.setFocusable(true);
        // View all.
        this.setSize(600,350);
        this.setVisible(true);
    }
    
    public void conectarServerRMI() {
        try {
            Registry registry = LocateRegistry.getRegistry(URL,PORT);
            this.gestorPreus = (GestorInterface)registry.lookup(JNDI_NAME);
            
        } catch (NotBoundException e) {
            Utils.shownError(TDSLanguageUtils.getMessage("Consulta.RMIError"));
            System.exit(0);
        } catch (RemoteException e) {
            Utils.shownError(TDSLanguageUtils.getMessage("Consulta.RMIError"));
            System.exit(0);
        } catch (Exception e) {
            Utils.shownError(TDSLanguageUtils.getMessage("Aplication.ExcpGeneral"));
            System.exit(0);
        }
    }

    public void initComboProveidors(){
        ArrayList<Proveidor> lista = new ArrayList();
        this.conectarServerRMI();
        try{
            lista =this.gestorPreus.getProveidors();
            if(lista.isEmpty()){
                Utils.shownError("Aplication.ErrorNoRecurso");
                System.exit(0);
            }else{
                Object [] items = new Object [lista.size()] ;
				int z=0;
				for (int i=0;i<lista.size();i++){
					items[z++] = new LocalProveidor(lista.get(i).getId_proveidor(), lista.get(i).getNom(), lista.get(i).getPerc_descompte(), lista.get(i).getQuant_descompte());
				}
				DefaultComboBoxModel model2=new DefaultComboBoxModel(items);
				jComboBox.setModel(model2);
            }
         }catch (RemoteException e) {
             Utils.shownError(TDSLanguageUtils.getMessage("Consulta.ExcpGenRemota"));
         }catch (SQLException e) {
             Utils.shownError(TDSLanguageUtils.getMessage("Consulta.ConsultaBD"),TDSLanguageUtils.getMessage("Consulta.ErrorCargaCombo"));
         }
    }
    
    public void montarTabla(ArrayList<Preu_peca> lista){
        
        String [] registros = new String [3];
        tabla = new JTable(null, titulos);
        for (int i=0;i<lista.size();i++){
                registros[0]=lista.get(i).getMarcaCoche().getNom();
                registros[1]=lista.get(i).getTipoPeca().getNom();
                registros[2]=Utils.formato(lista.get(i).getPreu(),2);;
                model.addRow(registros);
            }
            tabla.setModel(model);
            
    }
    
    public void mostrarDescuentoCantidad(Proveidor proveidor){
       
        jLabel3.setText(Utils.formato(proveidor.getPerc_descompte(),2));
        jLabel4.setText(Utils.formato(proveidor.getQuant_descompte(),2));
    }
	class LocalProveidor {
		private int id;
		private String name;
		private float percDescompte;
		private int quantDescompte;

		public int getId() {
			return id;
		}
		public LocalProveidor(int id, String name, float percDescompte, int quantDescompte) {
			this.id = id;
			this.name = name;
			this.percDescompte = percDescompte;
			this.quantDescompte = quantDescompte;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}
		
		public float getPercDescompte() {
			return percDescompte;
		}
		public void setPercDescompte(float percDescompte) {
			this.percDescompte = percDescompte;
		}
		public int getQuantDescompte() {
			return quantDescompte;
		}
		public void setQuantDescompte(int quantDescompte) {
			this.quantDescompte = quantDescompte;
		}
		
		public boolean hasDescompte () {
			return percDescompte!=0.0F & quantDescompte!=0;
		}
		
		@Override
		public String toString() {
			return name;
		}
	}
}
